package com.getpebble.android.main.sections.settings.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.framework.fragment.PblListFragment;
import com.getpebble.android.common.model.LanguagePackModel;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.main.sections.settings.activity.LanguageSelectionActivity;
import com.getpebble.android.main.sections.settings.adapter.LanguagePackAdapter;
import com.getpebble.android.onboarding.activity.OnboardingActivity;

public class LanguagePackManagerFragment extends PblListFragment implements LoaderCallbacks<Cursor> {
    private static final String TAG = LanguagePackManagerFragment.class.getSimpleName();
    private CursorAdapter mCursorAdapter = null;
    private CursorLoader mCursorLoader = null;

    public int getLayoutId() {
        return R.layout.fragment_language_pack_manager;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Trace.debug(TAG, "init()");
        super.init(inflater, container, savedInstanceState);
        setDivider(new ColorDrawable(R.color.gray));
        setDividerHeight(1);
        setBackgroundColor(getResources().getColor(R.color.white));
        final boolean isOnboarding = getActivity() instanceof OnboardingActivity;
        if (!isOnboarding) {
            container.findViewById(R.id.onboarding_banner).setVisibility(8);
        }
        setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Activity activity = LanguagePackManagerFragment.this.getActivity();
                if (activity == null) {
                    Trace.debug(LanguagePackManagerFragment.TAG, "Handling click event but activity is null; dropping click");
                    return;
                }
                Fragment nextFragment;
                PblDeviceRecord record = PebbleApplication.getConnectedDeviceRecord();
                Cursor cursor = (Cursor) LanguagePackManagerFragment.this.mCursorAdapter.getItem(position);
                String languageName = cursor.getString(cursor.getColumnIndex("local_language_name"));
                String fileUrl = cursor.getString(cursor.getColumnIndex("file_url"));
                String isoLocale = cursor.getString(cursor.getColumnIndex("iso_locale"));
                Bundle args = LanguageSelectionConstants.createBundle(fileUrl, languageName, isoLocale, cursor.getInt(cursor.getColumnIndex("language_version")));
                boolean isLanguageAlreadyInstalled = record != null && ObjectUtil.nullCheckEquals(record.isoLocale, isoLocale);
                if (isLanguageAlreadyInstalled) {
                    nextFragment = new LanguageSelectionCompleteFragment();
                    nextFragment.setArguments(args);
                } else {
                    nextFragment = new LanguageInstallFragment();
                    nextFragment.setArguments(args);
                }
                if (activity instanceof LanguageSelectionActivity) {
                    ((LanguageSelectionActivity) activity).switchScreenFragment(nextFragment);
                } else if (isOnboarding) {
                    ((OnboardingActivity) activity).switchScreenFragment(nextFragment);
                } else {
                    Trace.error(LanguagePackManagerFragment.TAG, "Unknown activity type; cannot switch fragment; finishing activity");
                    activity.finish();
                }
            }
        });
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        if (!PebbleApplication.isConnected()) {
            return new CursorLoader(getActivity(), LanguagePackModel.getRawQueryUri(), null, null, null, null);
        }
        String[] selectionArgs = LanguagePackModel.getSelectionArgsForRawQuery(PebbleApplication.getConnectedDeviceRecord().hwPlatform);
        switch (id) {
            case -1412611295:
                this.mCursorLoader = new CursorLoader(getActivity(), LanguagePackModel.getRawQueryUri(), null, null, selectionArgs, null);
                break;
        }
        return this.mCursorLoader;
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        final Activity activity = getActivity();
        if (activity == null) {
            Trace.debug(TAG, "Activity is null; ignoring onLoadFinished");
            return;
        }
        PblDeviceRecord record = PebbleApplication.getConnectedDeviceRecord();
        if (this.mCursorAdapter == null) {
            this.mCursorAdapter = new LanguagePackAdapter(activity, data, record == null ? null : record.isoLocale);
            setAdapter(this.mCursorAdapter);
        } else {
            this.mCursorAdapter.changeCursor(data);
        }
        if (this.mCursorAdapter.isEmpty()) {
            Trace.error(TAG, "No language packs found, cursor is empty. Exiting language selection");
            if (record != null) {
                Trace.error(TAG, "> HW platform: " + record.hwPlatform.getName() + " FW version: " + record.fwVersion);
            }
            Toast.makeText(activity, R.string.language_selection_error_message, 1).show();
            if (activity instanceof OnboardingActivity) {
                new Handler(activity.getMainLooper()).post(new Runnable() {
                    public void run() {
                        ((OnboardingActivity) activity).goToNextScreen();
                    }
                });
                return;
            } else if (activity instanceof LanguageSelectionActivity) {
                activity.finish();
                return;
            } else {
                Trace.error(TAG, "Unsupported activity: " + activity.getClass().getSimpleName());
            }
        }
        Trace.verbose(TAG, "Loaded cursor of size: " + this.mCursorAdapter.getCount());
        MobileAppBehavior.logLanguagePacksDisplayed(this.mCursorAdapter.getCount());
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        if (loader == this.mCursorLoader) {
            Cursor c = this.mCursorAdapter.getCursor();
            if (c != null) {
                c.close();
            }
            this.mCursorAdapter = null;
        }
    }

    public void onAttach(Activity activity) {
        Trace.debug(TAG, "onAttach()");
        super.onAttach(activity);
        activity.runOnUiThread(new Runnable() {
            public void run() {
                LanguagePackManagerFragment.this.initialize();
            }
        });
    }

    private void initialize() {
        Trace.debug(TAG, "initialize()");
        if (getActivity() == null) {
            Trace.debug(TAG, "initialize(); activity is null");
            return;
        }
        LoaderManager loaderManager = getLoaderManager();
        if (loaderManager != null) {
            loaderManager.initLoader(-1412611295, new Bundle(), this);
        }
    }
}
